package cmbchina.util;

import cmbchina.util.db.FlowDb;
import cmbchina.util.db.FlowFormDb;
import cmbchina.util.http.DbServiceRequestUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.flowable.app.model.runtime.CompleteFormRepresentation;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Created by zm on 17-11-12.
 */
public class RunScript {

    private static final Logger LOGGER = LoggerFactory.getLogger(RunScript.class);



    public static AjaxJson runScript(CompleteFormRepresentation completeTaskFormRepresentation,TaskService taskService,String taskId,String resultParmas,String processInstId,String taskDefinitionKey){
        LOGGER.info("====进入了runScript方法=======");
        FlowScriptRunUtils scriptRunUtils = new FlowScriptRunUtils();
        //将流程状态置为运行中
        FlowDb.updateFlowState(2, processInstId);
        AjaxJson ajaxJson =new AjaxJson();
        try {
            String script = "";
            if(completeTaskFormRepresentation.getValues().get("linuxScriptId")==null && completeTaskFormRepresentation.getValues().get("aixScriptId")==null){
                ajaxJson.setSuccess(false);
                ajaxJson.setMsg("该任务步骤没有配置脚本");
                LOGGER.error("该任务步骤没有配置脚本");
                FlowDb.updateFlowState(4, processInstId);

                //将任务节点改为失败 9527代表任务没有配置脚本
                FlowFormDb.updateFlowFormState(4,processInstId,taskDefinitionKey,"9527",ajaxJson.getMsg(),script);
                taskService.setVariableLocal(taskId, "result", ajaxJson.getMsg());
                return ajaxJson;
            }
            String scriptName = completeTaskFormRepresentation.getValues().get("linuxScriptId").toString();
            if(!completeTaskFormRepresentation.getValues().containsKey("hostname")){
                ajaxJson.setSuccess(false);
                ajaxJson.setMsg("该任务步骤没有配置主机名");
                LOGGER.error("该任务步骤没有配置主机名");
                FlowDb.updateFlowState(4, processInstId);

                //将任务节点改为失败 9527代表任务没有配置脚本
                FlowFormDb.updateFlowFormState(4,processInstId,taskDefinitionKey,"9527",ajaxJson.getMsg(),script);
                taskService.setVariableLocal(taskId, "result", ajaxJson.getMsg());
                return ajaxJson;
            }
            String hostname = completeTaskFormRepresentation.getValues().get("hostname").toString();
            String requestParams = "{\"host\":\""+ hostname +"\"}";
            //调用老看板接口查询判断调用linux脚本还是aix脚本
            AjaxJson ajaxJsonCheckScript = new DbServiceRequestUtil().CheckScriptNameRequest(requestParams);
            LOGGER.error("plat========"+ajaxJsonCheckScript.getMsg());
            if("AIX".equals(ajaxJsonCheckScript.getMsg())){
                scriptName = completeTaskFormRepresentation.getValues().get("aixScriptId").toString();
            }
            for(String key:completeTaskFormRepresentation.getValues().keySet()){

                scriptName = scriptName.replaceAll("#"+key+"#",completeTaskFormRepresentation.getValues().get(key).toString());
//                String keyLowerCase = key.toLowerCase();
//                LOGGER.error("key========"+keyLowerCase+completeTaskFormRepresentation.getValues().get(key));
//                if("host".equals(keyLowerCase) || "hostname".equals(keyLowerCase)){
//                    String requestParams = "{\"host\":\""+completeTaskFormRepresentation.getValues().get(key)+"\"}";
//                    //调用老看板接口查询判断调用linux脚本还是aix脚本
//                    AjaxJson ajaxJsonCheckScript = new DbServiceRequestUtil().CheckScriptNameRequest(requestParams);
//                    LOGGER.error("plat========"+ajaxJsonCheckScript.getMsg());
//                    if("AIX".equals(ajaxJsonCheckScript.getMsg())){
//                        scriptName = completeTaskFormRepresentation.getValues().get("aixScriptId").toString();
//                    }
//                }
//                if(!("linuxScriptId".equals(key)||"aixScriptId".equals(key))){
//                    script = script + " -" + key +" "+completeTaskFormRepresentation.getValues().get(key);
//                }
            }
            script = scriptName;
            //跟新缓存
            ScriptResult scriptResult = new ScriptResult();

            scriptResult = scriptRunUtils.runScript(script);
            taskService.setVariable(taskId,"returnCode",scriptResult.getReturnCode());
            taskService.setVariableLocal(taskId, "result", scriptResult.getResult());
            taskService.setVariableLocal(taskId, "scriptShCommon", script);
            LOGGER.error("配置了输出："+resultParmas);

            if(scriptResult.getReturnCode()!=0){
                ajaxJson.setSuccess(false) ;
                ajaxJson.setCode(scriptResult.getReturnCode()+"");
                ajaxJson.setMsg(scriptResult.getResult()+"");
                if(resultParmas!=null&&!"".equals(resultParmas)){
//                    ajaxJson.setSuccess(true) ;
                    taskService.setVariable(taskId,resultParmas,scriptResult.getReturnCode());
                }
                //将任务节点改为失败
                FlowFormDb.updateFlowFormState(4,processInstId,taskDefinitionKey,scriptResult.getReturnCode()+"",scriptResult.getResult(),script);
            }
            else{
                ajaxJson.setSuccess(true);
                ajaxJson.setCode(scriptResult.getReturnCode()+"");
                ajaxJson.setMsg(scriptResult.getResult()+"");
                //处理白名单密码问题
                List<String> resultList = scriptResult.getResultList();
                for(String rs : resultList){
                    if(StringUtils.isNotBlank(rs)){
                        String rsTrim = rs.trim();
                        if(rsTrim.indexOf("!!")==0){
                            rsTrim = rsTrim.substring(1,rsTrim.length()-2);
                            String [] rsArray = rsTrim.split(":");
                            if(rsArray.length==2){

                                taskService.setVariable(taskId,"whiteListUser",rsArray[0]);
                                taskService.setVariable(taskId,"whiteListPassword",rsArray[1]);
                            }
                        }
                    }
                }
                LOGGER.error("SystemCacheUtil.whiteListPasswordMap============" + SystemCacheUtil.whiteListPasswordMap);
                if(SystemCacheUtil.whiteListPasswordMap.containsKey(processInstId)){
                    taskService.setVariable(taskId,"whiteListPassword",SystemCacheUtil.whiteListPasswordMap.get(processInstId));
                }
                //将任务节点改为成功
                FlowFormDb.updateFlowFormState(5,processInstId,taskDefinitionKey,scriptResult.getReturnCode()+"",scriptResult.getResult(),script);

            }

        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.setSuccess(false) ;
            ajaxJson.setCode("400");
            ajaxJson.setMsg(e.getMessage());
            //将任务节点改为失败
            FlowFormDb.updateFlowFormState(4,processInstId,taskDefinitionKey,ajaxJson.getCode()+"",ajaxJson.getMsg(),"");
            taskService.setVariable(taskId, "returnCode", "10000");
            taskService.setVariableLocal(taskId, "result", e.getMessage());
//            formService.saveFormInstanceByFormModelId(completeTaskFormRepresentation.getValues(), completeTaskFormRepresentation.getFormId(), taskId, task.getProcessInstanceId());
        }
        if(ajaxJson.isSuccess() || (resultParmas!=null&&!"".equals(resultParmas))){

            taskService.completeTaskWithForm(taskId, completeTaskFormRepresentation.getFormId(),
                    completeTaskFormRepresentation.getOutcome(), completeTaskFormRepresentation.getValues());

            LOGGER.info("task count"+taskService.createTaskQuery().processInstanceId(processInstId).count());
            LOGGER.error("脚本执行："+ajaxJson.isSuccess());
            LOGGER.info("脚本执行："+ajaxJson.isSuccess());
            int state = ajaxJson.isSuccess()?5:4;
            //将流程状态置为运行成功
            FlowDb.updateFlowState(state, processInstId);
//            if(FlowFormDb.isEnd(processInstId)){
//                LOGGER.info("脚本执行："+ajaxJson.isSuccess());
//                int state = ajaxJson.isSuccess()?5:4;
//                //将流程状态置为运行成功
//                FlowDb.updateFlowState(state, processInstId);
//            }else{
//                int state = ajaxJson.isSuccess()?5:4;
//                //将流程状态置为运行成功
//                FlowDb.updateFlowState(state, processInstId);
//            }
        }else{
            //将流程状态置为运行失败
            FlowDb.updateFlowState(4, processInstId);
        }
        return ajaxJson;
    }
}
